#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date    : 2015-01-08 09:00:19
# @Author  : Your Name (Netxy@vip.qq.com)
# @Link    : http://www.itspas.com
# @Version : $Id$

import os
import sys
import json
import _winreg

class utils:
	@staticmethod
	def get_json():
		json_json = {'default':{'PATH':[]}}
		path_json = os.path.abspath(os.path.dirname(__file__) + '/data.data')
		if not os.path.exists(path_json):
			return json_json
		file_json = open(path_json)
		content = file_json.read()
		file_json.close()
		return json_json if len(content) == 0 else json.loads(content)
	
	@staticmethod
	def update_json(json_json):
		path_json = os.path.abspath(os.path.dirname(__file__) + '/data.data')
		if not os.path.exists(os.path.dirname(path_json)):
			os.makedirs(os.path.dirname(path_json))
		content = json.dumps(json_json)
		if len(content) > 0:
			file_json = open(path_json,'wb')
			file_json.write(content)
			file_json.close()
			
			path_bat = os.path.abspath(os.path.dirname(__file__) + '/AutoPath.bat')
			file_bat = open(path_bat,'wb')
			file_bat.write('@ECHO OFF\n')
			for k in json_json['default']:
				if k == 'PATH':
					for v in json_json['default'][k]:
						file_bat.write('SET PATH=%sPATH%s;%s;\n' % ('%','%',v))
				else:
					file_bat.write('SET %s=%s\n' % (k,json_json['default'][k]))
			file_bat.close()
			
	
	@staticmethod
	def help():
		print 'Use:'
		print '\tevn init'
		print '\tevn add [name] path'
		print '\tevn del key'
		print '\tevn cfg name [save|remove]'
		print '\tevn view'
		
	@staticmethod
	def handle_add():
		key = 'PATH' if len(sys.argv) < 4 else sys.argv[2]
		value = sys.argv[2 if key == 'PATH' else 3] if len(sys.argv) > 2 else None
		if value:
			json_json = utils.get_json()
			if key == 'PATH':
				value = os.path.abspath(os.getcwd()) if value == '.' else value
				if value not in json_json['default'][key]:
					json_json['default'][key].append(value)
			else:
				json_json['default'][key] = os.path.abspath(value)
			utils.update_json(json_json)
			
	@staticmethod
	def handle_del():
		value = sys.argv[2] if len(sys.argv) > 2 else None
		if value:
			json_json = utils.get_json()
			if value.isdigit() and len(json_json['default']['PATH']) > int(value):
				json_json['default']['PATH'].pop(int(value))
			elif value in json_json['default'].keys():
				json_json['default'].pop(value)
			utils.update_json(json_json)
	
	@staticmethod
	def handle_cfg():
		value = sys.argv[2] if len(sys.argv) > 2 else None
		if value:
			json_json = utils.get_json()
			if 'remove' in sys.argv and value in json_json:
				json_json.pop(value)
			elif 'save' in sys.argv:
				json_json[value] = json_json['default']
			elif value in json_json:
				json_json['default'] = json_json[value] 
			utils.update_json(json_json)
			
	@staticmethod
	def handle_view():
		json_json = utils.get_json()
		for cfg in json_json.keys():
			print '%s' % cfg
			for i in xrange(len(json_json[cfg]['PATH'])):
				print '\t%i:%s' % (i,json_json[cfg]['PATH'][i])
			for key in json_json[cfg]:
				if key == 'PATH':
					continue
				print '\t%s:%s' % (key,json_json[cfg][key])
				
	@staticmethod
	def handle_init():
		key = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER,'Software\Microsoft\Command Processor',0,_winreg.KEY_ALL_ACCESS)
		_winreg.SetValueEx(key,'AutoRun',0,_winreg.REG_SZ,os.path.abspath(os.path.dirname(__file__) + '/AutoPath.bat'))
		_winreg.FlushKey(key)
		_winreg.CloseKey(key)
		print 'init successful!'
		

if __name__ == "__main__":
	if len(sys.argv) <= 1 or sys.argv[1] == '-help':
		utils.help()
	else:
		hds = {'init':utils.handle_init,'add':utils.handle_add,'del':utils.handle_del,'cfg':utils.handle_cfg,'view':utils.handle_view}
		if sys.argv[1] in hds:
			hds[sys.argv[1]]();